<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 给定一个链表，两两交换其中相邻的节点，并返回交换后的链表。

    输入: 1->2->3->4
    输出: 2->1->4->3 -->

    <script>
        function swapPairs(head) {
            if (!head || !head.next) {
                return head
            }
            var dummy = {
                next: head
            }
            let node1, node2, p = dummy;
            while ((node1 = p.next) && (node2 = p.next.next)) {
                node1.next = node2.next;
                node2.next = node1;
                p.next = node2;

                p = node1;
            }
            return dummy.next;
        }

        // 第二遍 
        // 123456
        function swapPairs(head) {
            var dummy = { next: head };
            var p = dummy;
            var node1, node2;

            while ((node1 = p.next) && (node2 = p.next.next)){
                node1.next = node2.next;
                node2.next = node1;
                p.next = node2;
                p = node1;
            }
            return dummy.next;
        }
    </script>
</body>

</html>